import React, {Component} from "react"
import {observer} from "mobx-react"
import {Button, Col, Input, Cascader, Progress, Row, Select, Space, Spin, Table, Modal} from 'antd'
import {Link, RouteComponentProps, withRouter} from 'react-router-dom';
import {PlusOutlined} from '@ant-design/icons';
import routes from "../../config/routes";
import "./styles.less"
import Container from '../../components/Container'
import formatDate from '../../utils/formatDate'
import store from "./store";
import {CascaderOptionType} from "antd/lib/cascader";

const {Option} = Select;

//搜索  

interface Search {
    name: string
    setName: (val: string) => void
    oneDomains: Array<CascaderOptionType> | undefined
    twoDomains: Array<CascaderOptionType> | undefined
    one: number | undefined
    setOne: (val: number) => void
    two: number | undefined
    setTwo: (val: number) => void
    username: string
    setUsername: (val: string) => void
    onClick: () => void
    init: () => void
}

const Search: React.FC<Search> = ({onClick, name, one, two, oneDomains, twoDomains, username, setName, setOne, setTwo, setUsername, init}) => {
    return (
        <Space className='space'>
            <Input
                className='app-exp-input input'
                addonBefore='系统名称：'
                placeholder='请输入应用系统名称'
                style={{minWidth: 180}}
                value={name}
                onChange={(e) => {
                    setName(e.target.value)
                }}
            />
            <label>一级域：</label>
            <Select placeholder='请选择一级域' style={{minWidth: 180}} value={one} onChange={val => {
                setOne(val)
            }}>
                {
                    oneDomains?.map((val) => {
                        // @ts-ignore
                        return <Select.Option key={val.value} value={val.value}>{val.label}</Select.Option>
                    })
                }
            </Select>
            <label>二级域：</label>
            <Select placeholder='请选择二级域' style={{minWidth: 180}} value={two} onChange={val => {
                setTwo(val)
            }}>
                {
                    twoDomains?.map((val) => {
                        // @ts-ignore
                        return <Select.Option key={val.value} value={val.value}>{val.label}</Select.Option>
                    })
                }
            </Select>
            <Input
                className='app-exp-input input'
                addonBefore='负责人：'
                placeholder='请输入应用负责人'
                value={username}
                onChange={(e) => {
                    setUsername(e.target.value)
                }}
            />
            <Button className='app-but' type='primary' onClick={() => onClick()}>查询</Button>
            <Button onClick={() => init()}>重置</Button>
        </Space>

    )
}


@observer
class Index extends Component<RouteComponentProps, {}> {
    componentDidMount(): void {
        store.GetDomain()
        store.GetNamespaceList()
    }

    tableChange = (e: any) => {
        store.page_num = e.current
        store.GetNamespaceList()
    }

    handleCancel = async (e: any) => {
        store.delete_name_en = ''
        store.beOffline = false // 下线
    };
    handleDelNs = async () => {
        await store.deleteNamespace()
        store.delete_name_en = ''
        store.beOffline = false // 下线
    }
    success = () => {
        Modal.success({
            content: '下线业务系统操作成功！',
        });
    }
    error = () => {
        Modal.error({
            title: '操作失败',
            content: '请先暂停该业务下的有用应用',
        });
    }

    render() {
        const {systems, page_num, page_size, total, username, one, two, name, domains, twoDomains, beOffline} = store
        return (
            <Container title='业务系统管理' className='system-page'>
                {/* 列表内容开始 */}
                <section className="system-content">
                    {/* 按钮框 */}
                    <Button type='primary' icon={<PlusOutlined/>} style={{marginBottom: 20}} onClick={() => {
                        this.props.history.push(routes.system_create)
                    }}>创建业务系统</Button>
                    <Space size='middle' className="content-input">
                        <Search
                            oneDomains={domains}
                            twoDomains={twoDomains}
                            one={one}
                            two={two}
                            name={name}
                            username={username}
                            onClick={() => {
                                store.page_num = 1
                                store.GetNamespaceList()
                            }}
                            init={() => {
                                store.initParams()
                            }}
                            setName={(val) => {
                                console.log(val)
                                store.name = val
                            }}
                            setOne={(val) => {
                                store.one = val
                                store.twoDomains = undefined
                                // @ts-ignore
                                for (let i = 0; i < domains.length; i++) {
                                    if (domains[i].value === val) {
                                        if (domains[i].children) store.twoDomains = domains[i].children
                                        break
                                    }
                                }
                            }}
                            setTwo={(val) => {
                                store.two = val
                            }}
                            setUsername={(val) => {
                                store.username = val
                            }}/>
                    </Space>

                    {/* 列表 */}
                    <Spin delay={300} tip='加载中...' spinning={false}>
                        <Table columns={[
                            {
                                title: '系统名称',
                                width: 120,
                                dataIndex: 'name_cn',
                                // fixed: 'left',
                                align: 'center',
                                render: (text, {name_en}) => <Link
                                    to={{pathname: `${routes.system_details}/${name_en}`}}>{text}</Link>
                            },
                            {
                                title: '一级域',
                                width: 120,
                                dataIndex: 'top_level_domain',
                                align: 'center'
                            }, {

                                title: '二级域',
                                width: 120,
                                dataIndex: 'second_level_domain',
                                align: 'center',
                            },
                            {
                                title: '仓库类型',
                                width: 100,
                                dataIndex: 'is_private',
                                align: 'center',
                                render: (text) => {
                                    return (text === "1" ? <span style={{color: '#f00'}}>私有</span> : '公有');
                                }
                            },
                            {
                                title: '镜像仓库',
                                width: 150,
                                dataIndex: 'hub_name',
                                align: 'center',

                            },
                            // {
                            //     title: 'APP_NUM',
                            //     dataIndex: 'svc_number',
                            //     align: 'center',
                            // },
                            {
                                title: '配额',
                                width: 180,
                                dataIndex: 'pod_number',
                                align: 'center',
                                render: (text, record) => (
                                    <div>
                                        CPU：{record.cpu}Core；内存：{record.cpu}GB；<br/>
                                        磁盘：{record.disk}GB；
                                        {
                                            record.gpu ? <span>{record.cpu}个</span> : null
                                        }
                                    </div>
                                ),
                            },
                            // {
                            //     title: '资源平均利用率',
                            //     dataIndex: 'cpu',
                            //     align: 'center',
                            //     render: (text, record) => (
                            //         <Row>
                            //             <Col span={8}>CPU：</Col>
                            //             <Col span={16}>
                            //                 <Progress strokeColor={{
                            //                     '0%': '#108ee9',
                            //                     '100%': '#87d068',
                            //                 }} percent={record.cpu} size="small" status="active"/>
                            //             </Col>
                            //             <Col span={8}>内存：</Col>
                            //             <Col span={16}>
                            //                 <Progress strokeColor={{
                            //                     '0%': '#108ee9',
                            //                     '100%': '#87d068',
                            //                 }} percent={record.mem} size="small" status="active"/>
                            //             </Col>
                            //             {record.gpu ?
                            //                 <Col span={8}>GPU：</Col> : null}
                            //             {record.gpu ? <Col span={16}>
                            //                 <Progress strokeColor={{
                            //                     '0%': '#108ee9',
                            //                     '100%': '#87d068',
                            //                 }} percent={record.gpu} size="small" status="active"/>
                            //             </Col> : null}
                            //         </Row>
                            //     ),
                            // },
                            {
                                title: '负责人',
                                width: 120,
                                dataIndex: 'real_name',
                                align: 'center',
                            }, {
                                title: '创建时间',
                                dataIndex: 'created_at',
                                // fixed: 'right',
                                width: 150,
                                align: 'center',
                                render: (date) => formatDate(new Date(date))
                            }, {
                                title: '操作',
                                dataIndex: 'action',
                                // fixed: 'right',
                                width: 150,
                                align: 'center',
                                render: (text, {id,name_en}) => {
                                    return (
                                        <Select placeholder="选择操作" onChange={(value: any) => {
                                            if (value === '1') {
                                                this.props.history.push(routes.deployment)
                                            } else if (value === '2') {
                                                this.props.history.push(`${routes.member}/${id}`)
                                            } else if (value == '3') {
                                                this.props.history.push(`${routes.system_create}/${name_en}`)
                                            } else if (value == '4'){
                                                store.delete_name_en = name_en
                                                store.beOffline = true
                                            }
                                        }}>
                                            <Option value="1"><a>创建应用</a></Option>
                                            <Option value="2"><a>管理成员</a></Option>
                                            <Option value="3"><a>编辑</a></Option>
                                            <Option value="4"><a>下线</a></Option>
                                        </Select>
                                    )
                                },
                            },
                        ]} scroll={{x: 1060}} dataSource={[...systems]}
                               rowKey={(record: any) => record.id}
                               pagination={{
                                   current: page_num, // 当前页数
                                   pageSize: page_size,
                                   total: total,
                               }}
                               onChange={this.tableChange}
                        />
                    </Spin>
                </section>
                {/* 列表内容结束 */}
                <Modal className='down'
                    visible={beOffline}
                    onOk={this.handleDelNs}
                    onCancel={this.handleCancel}
                    okText='确认'
                    cancelText='取消'
                >
                    <h2>下线业务系统</h2>
                    <h4 >你确定下线业务系统吗？</h4>
                    <p className='ask'>（请先暂停该业务系统下的所有应用，前往暂停应用)</p>
                </Modal>

            </Container>
        )

    }

}


export default withRouter(Index as any)
